package com.bsoft.gol.hcs.specialist.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.request.QueryOperativeListRequest;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.specialist.entity.DiseaseSpeciesRelate;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Description: 病种关联数据记录dao
 * @Author: zhaorb
 * @Date: 2020/7/20 14:56
 **/
public abstract class DiseaseSpeciesRelateDAO extends HibernateSupportDelegateDAO<DiseaseSpeciesRelate> {


    @DAOMethod(sql = " from DiseaseSpeciesRelate where diseaseTypeId =:diseaseTypeId and relateType=:relateType ")
    public abstract List<DiseaseSpeciesRelate>  queryDiseaseSpeciesRelateList(@DAOParam("diseaseTypeId") Long diseaseTypeId,@DAOParam("relateType") String relateType);

    @DAOMethod(sql = " from DiseaseSpeciesRelate where diseaseTypeId =:diseaseTypeId  ")
    public abstract List<DiseaseSpeciesRelate> queryDiseaseSpeciesRelateListById(@DAOParam("diseaseTypeId") Long diseaseTypeId);


    @DAOMethod(sql = "delete from DiseaseSpeciesRelate where diseaseTypeId =:diseaseTypeId")
    public abstract void deleteDiseaseSpeciesRelateId(@DAOParam("diseaseTypeId") Long diseaseTypeId);

    @DAOMethod(sql = "select COUNT(1) from DiseaseSpeciesRelate where  relateRecordId = :indexId and relateType='4' ")
    public abstract Long getCountByIndexId(@DAOParam("indexId")String indexId);

    public List<PatientIndexTypeResp> queryIndexTypeByDiseaseTypeId(final QueryOperativeListRequest request) {
        HibernateStatelessResultAction<List<PatientIndexTypeResp>> action = new AbstractHibernateStatelessResultAction<List<PatientIndexTypeResp>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getIndexTypeStringByDiseaseTypeId(request);
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                int first = request.getPageNo() > 0 ? (request.getPageNo() - 1) * request.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(request.getPageSize());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                List<PatientIndexTypeResp> listResps = new ArrayList<>();
                for (Map map : dbList) {
                    listResps.add(ConversionUtils.convert(map, PatientIndexTypeResp.class));
                }
                setResult(listResps);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 根据病种id获取关联手术信息
     * @param qo
     * @return
     */
    public List<OperativeRecordResponse> queryRelateOperativeInfoList(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<OperativeRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<OperativeRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT record_id as operativeRecordId,relate_name as operativeName,gmt_create as operativeTime from fus_disease_relate_list WHERE disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and gmt_create >=:beginTime and gmt_create <=:endTime and relate_type ='3' order by gmt_create ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<OperativeRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, OperativeRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    /**
     *
     * 根据病种id获取关联药品信息
     * @param qo
     * @return
     */
    public List<MedicalRecordResponse> queryRelateMedicalInfoList(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<MedicalRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<MedicalRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select record_id as medicalId,relate_name as medicalName from fus_disease_relate_list WHERE disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and gmt_create >=:beginTime and gmt_create <=:endTime and relate_type ='6' order by gmt_create ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<MedicalRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, MedicalRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    /**
     * 获取病种配置的的关联指标信息
     * @param qo
     * @return
     */
    public List<CrucialRecordResponse> queryRelateInspectionReportInfo(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<CrucialRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<CrucialRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT DISTINCT " +
                        " fl.relate_record_id AS indexType, " +
                        " fl.relate_name AS indexName, " +
                        " fr.hpi_code AS indexHpiCode,fl.index_result_type,fl.gmt_create " +
                        "FROM " +
                        " fus_disease_relate_list fl left join fus_crucial_index_record fr on fl.relate_record_id = fr.index_id " +
                        "WHERE disease_type_id=:diseaseTypeId ");
                sqlBuilder.append(" and fl.gmt_create >=:beginTime and fl.gmt_create <=:endTime and fl.relate_type = '4' order by fl.index_result_type,fl.gmt_create ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<CrucialRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, CrucialRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    /**
     *
     * 获取病种配置的的治疗信息
     * @param qo
     * @return
     */
    public List<TreatmentRecordResponse> queryTreatmentInfo(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<TreatmentRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<TreatmentRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select relate_record_id as treatmentCode,relate_name as treatmentName from fus_disease_relate_list WHERE disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and gmt_create >=:beginTime and gmt_create <=:endTime and relate_type ='5' order by gmt_create ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<TreatmentRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, TreatmentRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    private StringBuffer getIndexTypeStringByDiseaseTypeId(QueryOperativeListRequest request) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(" select DISTINCT relate_record_id itemId, relate_name   itemName,unit ,description  from fus_disease_relate_list d" +
                " left join fus_crucial_index_record c on d.relate_record_id=c.index_id  WHERE  relate_type = '4'  ");


        if (StringUtils.isNotEmpty(request.getDiseaseTypeIdArr())) {
            stringBuffer.append(" and disease_type_id in ( " + request.getDiseaseTypeIdArr() + ") ");
        }else{
            if (StringUtils.isNotEmpty(request.getDiseaseTypeId().toString())) {
                stringBuffer.append(" and disease_type_id= " + request.getDiseaseTypeId() + " ");
            }
        }
        return stringBuffer;
    }

}
